const express = require('express');
const router = express.Router();

const userController = require('../controllers/userController');
const { 
  authenticateToken, 
  requireAdmin,
  requireSelfOrAdmin
} = require('../middleware/auth');
const { 
  validateSearch,
  validatePagination,
  validateObjectId,
  handleValidationErrors
} = require('../middleware/validation');
const { body, param } = require('express-validator');

/**
 * @route   GET /api/v1/users
 * @desc    获取用户列表（管理员）
 * @access  Private (Admin)
 */
router.get(
  '/',
  authenticateToken,
  requireAdmin,
  validatePagination,
  validateSearch,
  userController.getUserList
);

/**
 * @route   GET /api/v1/users/stats
 * @desc    获取用户统计信息（管理员）
 * @access  Private (Admin)
 */
router.get(
  '/stats',
  authenticateToken,
  requireAdmin,
  userController.getUserStats
);

/**
 * @route   GET /api/v1/users/:userId
 * @desc    获取用户详情
 * @access  Private (Self or Admin)
 */
router.get(
  '/:userId',
  authenticateToken,
  validateObjectId('userId'),
  requireSelfOrAdmin,
  userController.getUserById
);

/**
 * @route   PUT /api/v1/users/:userId
 * @desc    更新用户信息
 * @access  Private (Self or Admin)
 */
router.put(
  '/:userId',
  authenticateToken,
  validateObjectId('userId'),
  requireSelfOrAdmin,
  [
    body('username')
      .optional()
      .trim()
      .isLength({ min: 2, max: 50 })
      .withMessage('用户名长度必须在2-50个字符之间')
      .matches(/^[a-zA-Z0-9\u4e00-\u9fa5_-]+$/)
      .withMessage('用户名只能包含字母、数字、中文、下划线和连字符'),
      
    body('phone')
      .optional()
      .matches(/^[\+]?[1-9][\d]{0,15}$/)
      .withMessage('请输入有效的手机号码'),
      
    body('profile.name')
      .optional()
      .trim()
      .isLength({ max: 100 })
      .withMessage('姓名长度不能超过100个字符'),
      
    body('profile.location')
      .optional()
      .trim()
      .isLength({ max: 200 })
      .withMessage('地址长度不能超过200个字符'),
      
    body('profile.bio')
      .optional()
      .trim()
      .isLength({ max: 500 })
      .withMessage('个人简介长度不能超过500个字符'),
      
    handleValidationErrors
  ],
  userController.updateUser
);

/**
 * @route   PUT /api/v1/users/:userId/status
 * @desc    更新用户状态（管理员）
 * @access  Private (Admin)
 */
router.put(
  '/:userId/status',
  authenticateToken,
  requireAdmin,
  validateObjectId('userId'),
  [
    body('status')
      .isIn(['active', 'inactive'])
      .withMessage('状态必须是: active, inactive 之一'),
    handleValidationErrors
  ],
  userController.updateUserStatus
);

/**
 * @route   PUT /api/v1/users/:userId/role
 * @desc    更新用户角色（管理员）
 * @access  Private (Admin)
 */
router.put(
  '/:userId/role',
  authenticateToken,
  requireAdmin,
  validateObjectId('userId'),
  [
    body('role')
      .isIn(['farmer', 'logistics', 'merchant', 'consumer', 'admin'])
      .withMessage('角色必须是: farmer, logistics, merchant, consumer, admin 之一'),
    handleValidationErrors
  ],
  userController.updateUserRole
);

/**
 * @route   PUT /api/v1/users/:userId/reset-password
 * @desc    重置用户密码（管理员）
 * @access  Private (Admin)
 */
router.put(
  '/:userId/reset-password',
  authenticateToken,
  requireAdmin,
  validateObjectId('userId'),
  [
    body('newPassword')
      .isLength({ min: 6 })
      .withMessage('密码长度至少6个字符')
      .matches(/^(?=.*[a-zA-Z])(?=.*\d)/)
      .withMessage('密码必须包含至少一个字母和一个数字'),
    handleValidationErrors
  ],
  userController.resetUserPassword
);

/**
 * @route   DELETE /api/v1/users/:userId
 * @desc    删除用户（管理员）
 * @access  Private (Admin)
 */
router.delete(
  '/:userId',
  authenticateToken,
  requireAdmin,
  validateObjectId('userId'),
  userController.deleteUser
);

module.exports = router;